In early JavaScript development, Namespace Pollution was a significant hurdle. When unrelated code shares a single set of global variable names, unpredictable collisions occur. Modern design shifts from a structureless attitude to Isolated Module Systems.
1. Functional Isolation (IIFE)
By wrapping code in an Immediately Invoked Function Expression (IIFE), we create a private scope. Variables like names are trapped inside the function, inaccessible to the global environment.
var internal = "secret";
console.log(internal);
})();
2. Object-Based Interfaces
To provide functionality to the outside world, a module returns an object acting as its public interface. This groups related methods (like name and number) under a single reclaimed global variable.
3. The Exports Pattern
A sophisticated variation involves passing an exports object into the IIFE. This allows the module to attach its API directly to a specific namespace target, providing flexibility in how the module is consumed.